package com.lwl.shua.class02;

import java.util.HashMap;
import java.util.Map;

/**
 * @author lwl
 * @Description TODO
 * @date 2025/9/7 09:10
 */
public class Code03ReceiveAndPrintOrderLine {

    static class Node {
        String info;
        int num;
        Node next;

        public Node(String info, int num) {
            this.info = info;
            this.num = num;
        }
    }

    static class MessageBox {
        Map<Integer, Node> headMap = new HashMap<>();
        Map<Integer, Node> tailMap = new HashMap<>();
        int targetNum = 1;

        public void receive(int num, String info) {
            Node node = new Node(info, num);
            headMap.put(num, node);
            tailMap.put(num, node);
            // 查看是否有自己+1的节点作为头，有的话，将其移到自己next，并从head中移除，自己也从tail中移除
            if (headMap.containsKey(num + 1)) {
                node.next = headMap.get(num + 1);
                headMap.remove(num + 1);
                tailMap.remove(num);
            }
            // 查看是否有自己-1的节点作为尾，有的话将自己作为其next，将自身从head中移除，将节点从tail中移除
            if (tailMap.containsKey(num - 1)) {
                tailMap.get(num - 1).next = node;
                tailMap.remove(num - 1);
                headMap.remove(num);
            }
            if (num == targetNum) {
                Node startNode = headMap.get(num);
                Node t = startNode;
                Node endNode = null;
                while (t != null) {
                    System.out.print(t.info + " ");
                    endNode = t;
                    t = t.next;
                }
                System.out.println();
                headMap.remove(startNode.num);
                tailMap.remove(endNode.num);
                targetNum = endNode.num + 1;
            }
        }
    }
    public static void main(String[] args) {
        // MessageBox only receive 1~N
        MessageBox box = new MessageBox();
        // 1....
        System.out.println("这是2来到的时候");
        box.receive(2,"B"); // - 2"
        System.out.println("这是1来到的时候");
        box.receive(1,"A"); // 1 2 -> print, trigger is 1
        box.receive(4,"D"); // - 4
        box.receive(5,"E"); // - 4 5
        box.receive(7,"G"); // - 4 5 - 7
        box.receive(8,"H"); // - 4 5 - 7 8
        box.receive(6,"F"); // - 4 5 6 7 8
        box.receive(3,"C"); // 3 4 5 6 7 8 -> print, trigger is 3
        box.receive(9,"I"); // 9 -> print, trigger is 9
        box.receive(10,"J"); // 10 -> print, trigger is 10
        box.receive(12,"L"); // - 12
        box.receive(13,"M"); // - 12 13
        box.receive(11,"K"); // 11 12 13 -> print, trigger is 11

    }
}
